/******************************************************************************
 * Copyright (C) 2015  671643387@qq.com
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 *****************************************************************************/

#ifndef UGAME_BASE_ATOMICVALUE_H_
#define UGAME_BASE_ATOMICVALUE_H_

#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif

#include <cassert>
#include <cstdint>
#include <UGame/Macros.h>
#include <UGame/System/Mutex.h>
#include <UGame/System/LockGuard.h>
using UGame::System::LockGuard;
using UGame::System::Mutex;

namespace UGame {

    template<typename T>
    class AtomicValue
    {
    public:
        AtomicValue(const T &_Value) : _mutex(), _value(_Value) {  }
        ~AtomicValue(void){  }

        T operator++(void)
        {
            UMUTEX_LOCK_ASSERT(_Guard, _mutex);
            return ++_value;
        }

        T operator--(void)
        {
            UMUTEX_LOCK_ASSERT(_Guard, _mutex);
            return --_value;
        }

		AtomicValue& operator=(const T& _Value)
		{
            UMUTEX_LOCK_ASSERT(_Guard, _mutex);
			_value = _Value;
			return *this;
		}

        operator T(void) const { return _value; }

    private:
        Mutex _mutex;
        volatile T _value;
        DISALLOW_COPY_AND_ASSIGN(AtomicValue);
    };


    typedef AtomicValue<std::int8_t> AtomicValue_Int8;
    typedef AtomicValue<std::uint8_t> AtomicValue_UInt8;
    typedef AtomicValue<std::int16_t> AtomicValue_Int16;
    typedef AtomicValue<std::uint16_t> AtomicValue_UInt16;
    typedef AtomicValue<std::int32_t> AtomicValue_Int32;
    typedef AtomicValue<std::uint32_t> AtomicValue_UInt32;
    typedef AtomicValue<std::int64_t> AtomicValue_Int64;
    typedef AtomicValue<std::uint64_t> AtomicValue_UInt64;
}

#endif // UGAME_BASE_ATOMICVALUE_H_
